package cn.js.ccit.config;

import cn.js.ccit.pojo.User;
import cn.js.ccit.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService service;
//授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了===>用户授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        //拿到user对象
        User currentUser = (User) subject.getPrincipal();
        info.addStringPermission(currentUser.getPerms());//设置权限
        return info;
    }
//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了===>登录认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        User user = service.findUserByName(token.getUsername());
        if (user==null){//没有该用户
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        //将登陆用户放入到session中
        subject.getSession().setAttribute("loginUser",user);
        //密码认证
        return  new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
